<?php

namespace app\index\controller;

use think\Controller;
use think\Exception;

class User extends Controller
{
    public function login()
    {
        $session = session('o2o_user','', 'o2o');
        if(!empty($session)){
            return $this->redirect(url('index/index'));
        }
        return $this->fetch('');
    }

    public function register()
    {   //如果是post请求则保存数据，否则跳转页面
        if (request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['verifycode'])) {
                $this->error('验证码错误');
            }
            if ($data['password'] != $data['repassword']) {
                $this->error("两次输入密码不一致");
            }
            $data['code'] = mt_rand(100, 10000);
            $data['password'] = md5($data['password'] . $data['code']);

            try {
                $res = model('User')->add($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($res) {
                $this->success('注册成功', url('User/login'));
            } else {
                $this->error('注册失败');
            }


        } else {
            return $this->fetch('');
        }

    }

    public function logincheck()
    {
        if (!request()->isPost()) {
            $this->error('提交不合法');
        }
        $data = input('post.');
        try {
            $user = model('User')->getUserByUsername($data['username']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if(!$user || $user->status !=1){
             $this->error("用户不存在");
        }
        if(md5($data['password'].$user->code) != $user->password){
            $this->error("密码错误");
        }
         model('User')->updateById(['last_login_time'=>time()],$user->id);
        session('o2o_user',$user,'o2o');
        $this->success('登录成功',url('index/index'));
    }

    public function logout()
    {
        session( null,'o2o');
        $this->redirect(url('user/login'));
    }

}